''' 目标函数部分 '''
import config
import Distribution
from Distribution import CheckPendingDistribution

'''目标函数室时间的惩罚值  SPF   2024.9.9'''


def penalty_fun(schemesList, conflictsList, course_students, classrooms,distribution_penalty):
    penalty = []

    '''惩罚值总共包括以下几个方面：  SPF   2024.9.9'''
    # 1.计算所有的教室惩罚值
    # 2.计算所有的时间惩罚值
    # 3.学生冲突的惩罚值（由于是先排后选的策略，所以这个为0）
    # 4.约束的惩罚值（教学任务的优先级等约束条件）
    for schemes in schemesList:
        time_penalty, room_penalty, total_penalty = 0, 0, 0
        dis_penalty = CheckPendingDistribution(schemes, distribution_penalty)
        for task in schemes:
            room_penalty += task[5][0][1]
            time_penalty += task[5][1][-1]
        penalty.append((room_penalty, time_penalty,dis_penalty))

    # 学生冲突即学生冲突
    for i, conflicts in enumerate(conflictsList):
        stu_conflict = 0
        if not conflicts:
            for conflict in conflicts:
                # 学生的数量
                stu_nums = [len(students) for course, students in course_students if course == conflict[1]][0]
                # 与课程相关的教学任务（不冲突的的教学任务）
                # 每个班级的人数和
                task_num = [(tasks[3], tasks[5][0][0]) for tasks in schemesList[i] if
                            (tasks[1] == conflict[1] and tasks[6] == 0)]
                # 计算所有 tasks[3] 的和
                limit_num = sum(task[0] for task in task_num)
                # 计算每个班级所选教室的容纳人数和
                rid_list = [rid[1] for rid in task_num]
                room_num = 0
                for rid in rid_list:
                    room_num += [room[1] for room in classrooms if room[0] == rid][0]
                # 计算超出教室容量的学生人数，并累加到 stu_conflict 中
                min_capacity = min(limit_num, room_num)
                stu_conflict += (stu_nums - min_capacity) if (stu_nums - min_capacity) > 0 else 0
        # penalty[i] += (stu_conflict,)
        new_penalty = list(penalty[i])
        new_penalty[2] += stu_conflict
        penalty[i] = tuple(new_penalty)

    penalty = [list(pen) for pen in penalty]
    return penalty
